package userLimitService

import (
	"arabApi/app/api/models/userlimitModel"
	"arabApi/app/api/requests"
	"arabApi/app/api/requests/userlimitRequest"
	"arabApi/pkg/database"
	"arabApi/pkg/helpers"
	"github.com/spf13/cast"
)

type TreeList1 struct {
	ID       int         `json:"id"`
	ParentID int         `json:"parent_id"`
	Title    string      `json:"title"`
	Index    string      `json:"index"`
	Subs     []TreeList1 `json:"subs"`
	Order    int         `json:"order"`
}

func UserList(r requests.PageStruct) ([]map[string]interface{}, int64) {
	users, count := userlimitModel.UserList(r)

	list1 := make([]map[string]interface{}, len(users))
	for i, v := range users {
		user_map := helpers.S_struct_to_map(v)
		user_id := cast.ToInt64(user_map["id"])
		user_roles := userlimitModel.UserRoleName(user_id)
		user_roles_mame := ""
		for _, v1 := range user_roles {
			user_roles_mame += "," + cast.ToString(v1["role_name"])
		}

		//user_roles_mame = user_roles_mame[1:]
		user_map["user_role"] = user_roles_mame
		list1[i] = user_map
	}

	return list1, count
}

func UserAdd(r userlimitRequest.UserAdd) uint64 {
	user := new(userlimitModel.Users)
	return user.UserAdd(r)
}

func UserEdit(r userlimitRequest.UserAdd) error {
	user := new(userlimitModel.Users)
	return user.UserEdit(r)
}

func UserMsg(id string) userlimitModel.Users {
	return userlimitModel.GetMsgById(cast.ToInt64(id))
}

func UserRoleName(userId int64) ([]userlimitModel.UserRole, int64) {

	var count int64
	dd := database.DB.Model(userlimitModel.UserRole{})
	var users []userlimitModel.UserRole
	dd.Count(&count).Where("user_id = ?", userId).Find(&users)
	return users, count

}

func UserMenu(userid string) []TreeList1 {
	list := userlimitModel.UserRoleMenu(cast.ToInt64(userid))
	ll := getMenu1(list, 0)
	return ll
}

func getMenu1(menuList []map[string]interface{}, pid int) []TreeList1 {
	treeList := []TreeList1{}
	for _, v := range menuList {
		if cast.ToInt(v["p_id"]) == pid {
			child := getMenu1(menuList, cast.ToInt(v["id"]))
			node := TreeList1{
				ID:       cast.ToInt(v["id"]),
				Title:    cast.ToString(v["title"]),
				ParentID: cast.ToInt(v["p_id"]),
				Index:    cast.ToString(v["index"]),
				Order:    cast.ToInt(v["order"]),
			}
			if !helpers.Empty(child) {
				node.Subs = child
			}

			treeList = append(treeList, node)
		}
	}
	return treeList
}
